package com.eling.elcms.travel.dao.hibernate;

import com.eling.elcms.core.dao.hibernate.GenericDaoHibernate;
import com.eling.elcms.travel.dao.INonMemberGroupDao;
import com.eling.elcms.travel.model.NonMemberGroup;
import com.eling.elcms.travel.model.view.MemberGroupView;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository
public class NonMemberGroupDaoHibernate extends GenericDaoHibernate<NonMemberGroup, Long>
		implements INonMemberGroupDao {

	public NonMemberGroupDaoHibernate() {
		super(NonMemberGroup.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MemberGroupView> queryFit(Long pkServicePoint, Boolean checkIn,Boolean fstatus, Date startDate, Date endDate) {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT ");
		sql.append(" ser.name,ng.checkInDate,ng.checkOutDate,ng.pledge,ng.groupUnit,   ");
		sql.append(" ng.tourType,ng.chargeDate,ng.`status`,ng.fstatus ");
		sql.append(" FROM  ");
		sql.append(" `travel_nonmembergroup` ng  ");
		sql.append(" INNER JOIN travel_nonmemberregister nr ON ng.pkNonMemberGroup = nr.pkNonMemberGroup  ");
		sql.append(" INNER JOIN om_servicepoint ser ON ng.pkServicePoint = ser.pkServicePoint  ");
		sql.append(" INNER JOIN travel_roompersonalinfo rp ON rp.pkNonMemberRegister = nr.pkNonMemberRegister  ");
		sql.append(" WHERE  ");
		sql.append(" ng.pkServicePoint = " + pkServicePoint + " ");
		if(fstatus==null){
			sql.append(" AND ng.fstatus in (0,1)  ");
		}else if(fstatus) {
			sql.append(" AND ng.fstatus  = '1'  ");
		}else{
			sql.append(" AND ng.fstatus  = '0'  ");
		}
		sql.append(" AND ng.checkInDate >=:startDate  ");
		sql.append(" AND ng.checkOutDate <=:endDate  ");
		sql.append(" AND rp.checkIn = " + checkIn + " ");

		List<Object[]> oblist = getSession().createNativeQuery(sql.toString())
//				.setParameter("fstatus", fstatus)
				.setParameter("startDate", startDate)
				.setParameter("endDate", endDate).list();

		List<MemberGroupView> nmg = new ArrayList<>();
		for (int i = 0; i < oblist.size(); i++) {
			MemberGroupView non = new MemberGroupView();
			Object[] objects = oblist.get(i);
			non.setServicePoint(objects[0].toString());
			non.setStartDate(objects[1] == null ? (null) :(Date) objects[1]);
			non.setEndDate(objects[2] == null ? (null) :(Date) objects[2]);
			non.setPledge(objects[3] == null ? (0.00) :(Double) objects[3]);
			non.setGroupUnit(objects[4] == null ? null : objects[4].toString());
			non.setTourType(objects[5] == null ? null : objects[5].toString());
			non.setChargeDate(objects[6] == null ? null : (Date) objects[6]);
//			non.setStatus(objects[7] == null ? (null) :objects[7].toString());
			non.setFstatus(objects[8] == null ? false : new Boolean( objects[8].toString()));
			nmg.add(non);
		}
		return nmg;
	}
}
